import {
	API_URL
} from '@/env'
//判断字符串是否为空
const stringIsEmpty = function (obj){
    if(typeof obj == "undefined" || obj == null || obj == "" || obj == 0 || obj == "0"){
        return true;
    }else{
        return false;
    }
}

const createRandom = function (){
	return String(Math.random()).slice(2);
}

const getMinMaxRandom = function(minNum,maxNum){ 
    switch(arguments.length){ 
        case 1: 
            return parseInt(Math.random()*minNum+1,10); 
        break; 
        case 2: 
            return parseInt(Math.random()*(maxNum-minNum+1)+minNum,10); 
        break; 
            default: 
                return 0; 
            break; 
    } 
} 




const stringIsEmptyShowToast = function(obj,title,duration=2000){
	if(this.stringIsEmpty(obj)){
		uni.showToast({
			title:title,
			duration:duration,
			icon:'none',
		})
		// console.log(title);
		return false;
	} else {
		return true;
	}
}

//点击需要登录的方法
const needLoginJump = function(toUrl,jumpType=1){
	var p = this.authLogin();
	p.then(function(loginResult){
		if(loginResult['code']){
			if(jumpType == 1){
				uni.navigateTo({
					url:toUrl,
				})
			} else if(jumpType == 2){
				// console.log('switchTab===============');
				uni.switchTab({
					url:toUrl,
					success: (e) => {
						var page = getCurrentPages().pop();
						if (page == undefined || page == null) return;
						page.onLoad();
					}
				})
			}
			
		} else {
			uni.showToast({
				title: '为了更好的体验，需要授权登录！',
				mask: true,
				icon: 'none'
			})
		}
	});
}


const refreshLogin = function(){
	return new Promise(function(resolve, reject) {
			uni.showModal({ //getUserProfile接口只能是用户点击才能调用
				title: '温馨提示',
				content: '亲，登录超时，请重新授权微信登录后才能正常使用小程序功能',   //此处不能为空否则在ios上无法弹出
				success: (res) => {
					if(res.confirm){
						uni.getUserProfile({
							desc: '用于完善会员资料', // 声明获取用户个人信息后的用途，后续会展示在弹窗中，请谨慎填写
							success: (ress) => {
								let userObject = ress.userInfo;
								uni.login({
									success: (resss) => {
										if(resss.errMsg == "login:ok"){
											console.log(userObject);
											let code = resss.code;
											uni.request({
												// header: {
												// 	'content-type': 'application/x-www-form-urlencoded'
												// },
												url:API_URL+"index.php/api/user/wxlogin",
												method: 'POST',//接口类型 
												data: {
													'code':code,
													'avatar_url':userObject.avatarUrl,
													'city':userObject.city,
													'province':userObject.province,
													'gender':userObject.gender,
													'nick_name':userObject.nickName
												}, //接口需要的数据
												success: function(ressss) {
													
													console.log(ressss);
													if (ressss.data.code == 1) {
														uni.setStorageSync('token', ressss.data.data.token);
														uni.setStorageSync('uid', ressss.data.data.uid);
														uni.setStorageSync('gender', userObject.gender);
														uni.setStorageSync('avatar', userObject.avatarUrl);
														uni.setStorageSync('nickname', userObject.nickName);
														uni.setStorageSync('b_id', ressss.data.data.b_id);
														uni.setStorageSync('b_name', ressss.data.data.b_name);
														console.log(ressss.data.data.token);
														var loginResult = new Array();
														loginResult['code'] = true;
														loginResult['token'] = ressss.data.data.token;
														loginResult['uid'] = ressss.data.data.uid;
														loginResult['gender'] = ressss.data.data.gender;
														loginResult['avatar'] = ressss.data.data.avatarUrl;
														loginResult['nickname'] = ressss.data.data.nickName;
														loginResult['b_id'] = ressss.data.data.b_id;
														loginResult['b_name'] = ressss.data.data.b_name;
														resolve(loginResult);
														// that.login(res.data); //将接口返回的数据保存在全局变量中.
														//登录成功跳转首页或者你想跳转的地方... 
														//注意：如果时导航页 请用uni.switchTab
														// 		其他页面建议使用uni.reLaunch
													} else {
														uni.showToast({
															title: '授权登录失败，请联系管理员！',
															mask: true,
															icon: 'none'
														})
														var loginResult = new Array();
														loginResult['code'] = false;
														resolve(loginResult);
													}
															
															
												}
															
											})
											
										}
									}
								})
							},
							fail: (ress) => {
								uni.showToast({
									title: '为了更好的体验，需要授权登录！',
									mask: true,
									icon: 'none'
								 })
								 var loginResult = new Array();
								 loginResult['code'] = false;
								 resolve(loginResult);
							}
						})
			
			
					} else if (res.cancel) {
						uni.showToast({
							title: '您拒绝了请求,不能正常使用小程序',
							icon: 'error',
							duration: 2000
						});
									
					}
				}
			})
		
	}).catch((e) => {
		console.log(e)
	});
}


const authLogin = function (){
	return new Promise(function(resolve, reject) {
		let token = uni.getStorageSync('token');
		if(stringIsEmpty(token)){
			uni.showModal({ //getUserProfile接口只能是用户点击才能调用
				title: '温馨提示',
				content: '亲，授权微信登录后才能正常使用小程序功能',   //此处不能为空否则在ios上无法弹出
				success: (res) => {
					if(res.confirm){
						uni.getUserProfile({
							desc: '用于完善会员资料', // 声明获取用户个人信息后的用途，后续会展示在弹窗中，请谨慎填写
							success: (ress) => {
								let userObject = ress.userInfo;
								uni.login({
									success: (resss) => {
										if(resss.errMsg == "login:ok"){
											console.log(userObject);
											let code = resss.code;
											uni.request({
												// header: {
												// 	'content-type': 'application/x-www-form-urlencoded'
												// },
												url:API_URL+"index.php/api/user/wxlogin",
												method: 'POST',//接口类型 
												data: {
													'code':code,
													'avatar_url':userObject.avatarUrl,
													'city':userObject.city,
													'province':userObject.province,
													'gender':userObject.gender,
													'nick_name':userObject.nickName
												}, //接口需要的数据
												success: function(ressss) {
													
													console.log(ressss);
													if (ressss.data.code == 1) {
														uni.setStorageSync('token', ressss.data.data.token);
														uni.setStorageSync('uid', ressss.data.data.uid);
														uni.setStorageSync('gender', userObject.gender);
														uni.setStorageSync('avatar', userObject.avatarUrl);
														uni.setStorageSync('nickname', userObject.nickName);
														uni.setStorageSync('b_id', ressss.data.data.b_id);
														uni.setStorageSync('b_name', ressss.data.data.b_name);
														console.log(ressss.data.data.token);
														var loginResult = new Array();
														loginResult['code'] = true;
														loginResult['token'] = ressss.data.data.token;
														loginResult['uid'] = ressss.data.data.uid;
														loginResult['gender'] = ressss.data.data.gender;
														loginResult['avatar'] = ressss.data.data.avatarUrl;
														loginResult['nickname'] = ressss.data.data.nickName;
														loginResult['b_id'] = ressss.data.data.b_id;
														loginResult['b_name'] = ressss.data.data.b_name;
														resolve(loginResult);
														// that.login(res.data); //将接口返回的数据保存在全局变量中.
														//登录成功跳转首页或者你想跳转的地方... 
														//注意：如果时导航页 请用uni.switchTab
														// 		其他页面建议使用uni.reLaunch
													} else {
														uni.showToast({
															title: '授权登录失败，请联系管理员！',
															mask: true,
															icon: 'none'
														})
														var loginResult = new Array();
														loginResult['code'] = false;
														resolve(loginResult);
													}
															
															
												}
															
											})
											
										}
									}
								})
							},
							fail: (ress) => {
								uni.showToast({
									title: '为了更好的体验，需要授权登录！',
									mask: true,
									icon: 'none'
								 })
								 var loginResult = new Array();
								 loginResult['code'] = false;
								 resolve(loginResult);
							}
						})
			
			
					} else if (res.cancel) {
						uni.showToast({
							title: '您拒绝了请求,不能正常使用小程序',
							icon: 'error',
							duration: 2000
						});
									
					}
				}
			})
		} else {
			console.log('客户端判断已经登录');
			var loginResult = new Array();
			loginResult['code'] = true;
			loginResult['token'] = uni.getStorageSync('token');
			loginResult['uid'] = uni.getStorageSync('uid');
			loginResult['gender'] = uni.getStorageSync('gender');
			loginResult['avatar'] = uni.getStorageSync('avatar');
			loginResult['nickname'] = uni.getStorageSync('nickName');
			loginResult['b_id'] = uni.getStorageSync('b_id');
			loginResult['b_name'] = uni.getStorageSync('b_name');
			resolve(loginResult);
		}
	}).catch((e) => {
		console.log(e)
	});
	
}

const costomShowToast = function (title,duration=2000){
	uni.showToast({
		title:title,
		duration:duration,
		icon:'none',
	})
}
//数组追加
const addValueToArray = function (name,value){
	let arr = uni.getStorageSync(name);
	// console.log(typeof(arr));
	// console.log(arr);
	if(this.stringIsEmpty(arr)){
		arr = [];
	}
    // let arr=[1,2,3];
	//判断是否已经存在
	var isExist = arr.indexOf(value);
	if(isExist == -1){ //-1不存在，如果存在，则返回相应的下标
		arr[arr.length]=Number(value);
		uni.setStorageSync(name,arr);
	}
	
	// console.log(arr);
	
}
//判断是否一个字符串是否存在数组里
const checkValueIsArr = function (name,value){
	// console.log('============');
	// console.log(value);
	// console.log(typeof(Number(value)));
	// console.log('============');
	let arr = uni.getStorageSync(name);
	// console.log(arr);
	if(!this.stringIsEmpty(arr)){
		var isExist = arr.indexOf(Number(value));
		// console.log(isExist);
		if(isExist != -1){
			return true;
		}
	}
	return false;
}

const loadFontFaceFromWeb = function (name) {
	const urlttf = 	API_URL+'test/'+name+'.ttf'
	console.log("加载字体:"+urlttf);
	uni.loadFontFace({
		family: 'font-test',
		source: `url("${urlttf}")`
	})
}

const myStorageCache = function (key, value, seconds = 3600 * 24) {
	let nowTime = Date.parse(new Date()) / 1000;
	if (key && value) {
		let expire = nowTime + Number(seconds);
		uni.setStorageSync(key,JSON.stringify(value) + '|' +expire)
		console.log('已经把' + key + '存入缓存,过期时间为' + expire)
	} else if (key && !value) {
		let val = uni.getStorageSync(key);
		if (val) {
			// 缓存存在，判断是否过期
			let temp = val.split('|')
			if (!temp[1] || temp[1] <= nowTime) {
				uni.removeStorageSync(key)
				console.log(key + '缓存已失效')
				return '';
			} else {
				return JSON.parse(temp[0]);
			}
		}
	}

}

module.exports = {
	stringIsEmpty,
	createRandom,
	stringIsEmptyShowToast,
	authLogin,
	needLoginJump,
	costomShowToast,
	getMinMaxRandom,
	addValueToArray,
	checkValueIsArr,
	loadFontFaceFromWeb,
	myStorageCache,
	refreshLogin,
}